/**
 * Copyright � 2012 GestureSoft. ALL RIGHTS RESERVED.
 * This file contains proprietary and GestureSoft CONFIDENTIAL Information.
 * Use, disclosure or reproduction is prohibited.
 * 
 * @fileName VersionedItemHandler.as
 * @creationDate Aug 20, 2012
 * @author 
 * @version 1.0
 */
package com.gesturesoft.imultimax.model.initialsetup.versionedxmlhandlers.main
{
	import com.gesturesoft.imultimax.events.CompleteEvent;
	import com.gesturesoft.imultimax.events.CustomCompleteEvent;
	import com.gesturesoft.imultimax.events.CustomErrorEvent;
	import com.gesturesoft.imultimax.events.CustomProgressEvent;
	import com.gesturesoft.imultimax.model.ConfigLoader;
	import com.gesturesoft.imultimax.model.StyleParser;
	import com.gesturesoft.imultimax.model.ZipDownloader;
	import com.gesturesoft.imultimax.model.ZipExtractor;
	import com.gesturesoft.imultimax.model.application.ApplicationCurrentDomainUpdater;
	import com.gesturesoft.imultimax.model.application.ApplicationStyleUpdater;
	import com.gesturesoft.imultimax.model.application.interfaces.IApplicationUpdater;
	import com.gesturesoft.imultimax.model.cardmanager.CardDBManager;
	import com.gesturesoft.imultimax.model.cardmanager.ICardDBManager;
	import com.gesturesoft.imultimax.model.error.DataBaseError;
	import com.gesturesoft.imultimax.model.initialsetup.interfaces.IHandler;
	import com.gesturesoft.imultimax.model.interfaces.IConfigLoader;
	import com.gesturesoft.imultimax.model.interfaces.IStyleParser;
	import com.gesturesoft.imultimax.model.interfaces.IZipDownloader;
	import com.gesturesoft.imultimax.model.interfaces.IZipExtractor;
	import com.gesturesoft.imultimax.model.loader.events.LoadFaultEvent;
	import com.gesturesoft.imultimax.model.thememanger.ThemeManager;
	import com.gesturesoft.imultimax.model.utility.Companies;
	import com.gesturesoft.imultimax.model.utility.VersionChecker;
	import com.gesturesoft.imultimax.model.vo.CardTemplateXMLVO;
	import com.gesturesoft.imultimax.model.vo.ThemeDetailVO;
	import com.gesturesoft.imultimax.model.vo.ThemeXMLDetailVO;
	
	import flash.events.EventDispatcher;
	
	import mx.collections.ArrayCollection;

	public class VersionedItemHandler extends EventDispatcher implements IHandler
	{
		
		private var _versionDetails:Array;
		
		public function VersionedItemHandler(versionDetails:Array)
		{
			_versionDetails = versionDetails;
		}
		
		public function start():void
		{
			
			updateCompanies(_versionDetails[VersionChecker.COMPANY_DETAILS]);
			
		}
		
		//-----------------------------------------------START:Updating companies--------------------------------------------
		//START SUB:Downloading zip
		
		/**
		 * This is the function for binding company updation process
		 * 
		 * @functionName updateCompanies
		 * @creationDate Aug 20, 2012
		 * @author micmac
		 * @params companyDetails:ArrayCollection
		 */
		private function updateCompanies(companyDetails:ArrayCollection):void
		{
			
			if( companyDetails!=null && companyDetails.length > 0 )
			{
				
				var zipDownloader:IZipDownloader = new ZipDownloader(companyDetails);
				zipDownloader.addEventListener(CompleteEvent.COMPLETE, onZipDownloaded);
				zipDownloader.addEventListener(CustomProgressEvent.LOAD_COMPLETE, onZipComplete);
				zipDownloader.addEventListener(CustomProgressEvent.LOAD_PROGRESS, onZipProgress);
				zipDownloader.addEventListener(LoadFaultEvent.LOAD_FAILED, onZipDownloadFault);
				zipDownloader.download();
				
			}
			else
			{
				
				loadThemes();
				
			}
			
		}
		
		/**
		 * This is the function for dispatching zip progress event
		 * 
		 * @functionName onZipProgress
		 * @creationDate Sep 1, 2012
		 * @author micmac
		 * @params event:CustomProgressEvent
		 */
		private function onZipProgress(event:CustomProgressEvent):void
		{
			
			IHandler(this).dispatchEvent(event);
			
		}
		
		/**
		 * This is the function for sending zip loading complete
		 * 
		 * @functionName onZipComplete
		 * @creationDate Sep 1, 2012
		 * @author micmac
		 * @params event:CustomProgressEvent
		 */
		private function onZipComplete(event:CustomProgressEvent):void
		{
			
			IHandler(this).dispatchEvent(new CustomProgressEvent( CustomProgressEvent.LOAD_COMPLETE));
			
		}
		
		/**
		 * This is the function for sending zip download failed event
		 * 
		 * @functionName onZipDownloadFault
		 * @creationDate Sep 1, 2012
		 * @author micmac
		 * @params event:LoadFaultEvent
		 */
		private function onZipDownloadFault(event:LoadFaultEvent):void
		{
			
			IHandler(this).dispatchEvent(new CustomErrorEvent(CustomErrorEvent.ERROR_OCCURED, "Zip download failed"));
			
		}
		/**
		 * This is the function for extracting the downloaded zip 
		 * 
		 * @functionName onZipDownloaded
		 * @creationDate Aug 20, 2012
		 * @author micmac
		 * @params event:CompleteEvent
		 */
		private function onZipDownloaded(event:CompleteEvent):void
		{
			
			IZipDownloader( event.target ).removeEventListener(CompleteEvent.COMPLETE, onZipDownloaded, true);
			IZipDownloader( event.target ).removeEventListener(CompleteEvent.COMPLETE, onZipDownloaded, false);
			
			var updationDetails:ArrayCollection = ZipDownloader(event.object).assets4Updation;
			event.object = null;  //Nullify the ZipDownloader object
			event = null;
			
			extractZip(updationDetails);
			
		}
		//END SUB:Downloading zip
		
		//START SUB:Extracting zip contents
		
		/**
		 * This is the function for extracting zip contents
		 * 
		 * @functionName extractZip
		 * @creationDate Sep 1, 2012
		 * @author GestureSoft
		 * @params updationDetails:ArrayCollection
		 */
		private function extractZip(updationDetails:ArrayCollection):void
		{
			
			var zipExtractor:IZipExtractor = new ZipExtractor(updationDetails);
			zipExtractor.addEventListener( CompleteEvent.COMPLETE, onExtractionComplete );
			zipExtractor.extract();
			
		}
		
		/**
		 * This is the function for parsing the style and asset details
		 * from the extracted XML
		 * 
		 * @functionName onExtractionComplete
		 * @creationDate Aug 20, 2012
		 * @author micmac
		 * @params event:CompleteEvent
		 */
		private function onExtractionComplete(event:CompleteEvent):void
		{
			
			IZipExtractor( event.target ).removeEventListener(CompleteEvent.COMPLETE, onExtractionComplete, true);
			IZipExtractor( event.target ).removeEventListener(CompleteEvent.COMPLETE, onExtractionComplete, false);
			
			parseStyleAndAssets( ZipExtractor(event.object).assetDetails );
			
		}
		
		//END SUB:Extracting zip contents
		
		//START SUB:Parsing style and asset details
		
		/**
		 * This is the function for parsing the style and asset details in the extracted zip
		 * 
		 * @functionName parseStyleAndAssets
		 * @creationDate Sep 1, 2012
		 * @author micmac
		 * @params assetDetails:ArrayCollection
		 */
		private function parseStyleAndAssets(assetDetails:ArrayCollection):void
		{
			
			var styleParser:IStyleParser = new StyleParser( assetDetails );
			styleParser.addEventListener( CompleteEvent.COMPLETE, onStyleExtractionComplete );
			//stageSize = loadMsg;
			styleParser.parse();
			
		}
		
		/**
		 * This is the function for applying the extracted style and asset details
		 * 
		 * @functionName onStyleExtractionComplete
		 * @creationDate Aug 20, 2012
		 * @author micmac
		 * @params event:CompleteEvent		 */
		private function onStyleExtractionComplete(event:CompleteEvent):void
		{
			
			
			IStyleParser(event.target).removeEventListener(CompleteEvent.COMPLETE, onStyleExtractionComplete );
			
			var applicationUpdator:IApplicationUpdater = new ApplicationStyleUpdater(StyleParser(event.object).assetDetails, StyleParser(event.object).styles);
			
			try
			{
				
				applicationUpdator.update();
				
			} 
			catch(error:DataBaseError) 
			{
				/////////////////////////dispatch error///////////////
				return;
				
			}
			
			loadThemes();
			
		}
		
		//END SUB:Parsing style and asset details
		
		//-----------------------------------------------END:Updating companies--------------------------------------------
		
		//-----------------------------------------------START:Updating theme details--------------------------------------------
		//START SUB:Downloading themes
		/**
		 * This is the function for loding themes
		 * 
		 * @functionName loadThemes
		 * @creationDate Sep 1, 2012
		 * @author GestureSoft
		 * 
		 */
		private function loadThemes():void
		{
			
			if( _versionDetails[VersionChecker.THEME_DETAILS] )
			{
				
				var themeXMLDetailVO:ThemeXMLDetailVO  = _versionDetails[VersionChecker.THEME_DETAILS];
				var themeLoader:IConfigLoader = new ConfigLoader(themeXMLDetailVO.url);
				themeLoader.addEventListener(CompleteEvent.COMPLETE, onThemesLoaded);
				themeLoader.addEventListener(LoadFaultEvent.LOAD_FAILED, themesLoadFailed);
				themeLoader.loadConfig();
				
			}
			else
			{
				
				dispatchEvent(new CustomCompleteEvent(CustomCompleteEvent.COMPLETED, "Versioned XML handling complete", true, true));
				//loadCardTemplates();
			}
			
		}
		
		/**
		 * This is the function for parsing theme xml and update into DB
		 * 
		 * @functionName onThemesLoaded
		 * @creationDate Sep 1, 2012
		 * @author micmac
		 * @params event:CompleteEvent
		 */
		private function onThemesLoaded(event:CompleteEvent):void
		{
			
			var themeXMLDetailVO:ThemeXMLDetailVO = _versionDetails[VersionChecker.THEME_DETAILS];
			
			IConfigLoader( event.target ).removeEventListener( CompleteEvent.COMPLETE, onThemesLoaded );
			
			//Themes Parser
			trace( XML( ConfigLoader(event.object).data ) );
			var themeManager:ThemeManager = new ThemeManager();
			
			themeManager.process( XML( ConfigLoader(event.object).data ), themeXMLDetailVO.themeVersion);
			
			dispatchEvent(new CustomCompleteEvent(CustomCompleteEvent.COMPLETED, "Versioned XML handling complete", true, true));
			
			//loadCardTemplates();
			
		}
		
		/**
		 * This is the function for send event curresponding to theme load fault
		 * 
		 * @functionName themesLoadFailed
		 * @creationDate Sep 1, 2012
		 * @author micmac
		 * @params event:LoadFaultEvent
		 */
		private function themesLoadFailed(event:LoadFaultEvent):void
		{
			
			dispatchEvent(new CustomErrorEvent(CustomErrorEvent.ERROR_OCCURED, "Themes XML load failed"));
			
		}
		
		//END SUB:Downloading themes
		//-----------------------------------------------END:Updating theme details--------------------------------------------
		
		//////////////////////////////////////////////////START:Updating card template details/////////////////////////////////////////////
		/**
		 * This is the function for loding card templates
		 * 
		 * @functionName loadCardTemplates
		 * @creationDate Nov 12, 2012
		 * @author GestureSoft
		 * 
		 */
		/*private function loadCardTemplates():void
		{
			
			if( _versionDetails[VersionChecker.CARD_TEMPLATE_VERSION_DETAILS] )
			{
				
				var cardTemplateXMLVO:CardTemplateXMLVO  = _versionDetails[VersionChecker.CARD_TEMPLATE_VERSION_DETAILS];
				var cardTemplateLoader:IConfigLoader = new ConfigLoader(cardTemplateXMLVO.url);
				cardTemplateLoader.addEventListener(CompleteEvent.COMPLETE, onCardTemplatesLoaded);
				cardTemplateLoader.addEventListener(LoadFaultEvent.LOAD_FAILED, onCardTemplatesLoadFailed);
				cardTemplateLoader.loadConfig();
				
			}
			else
			{
				
				dispatchEvent(new CustomCompleteEvent(CustomCompleteEvent.COMPLETED, "Versioned XML handling complete", true, true));
				
			}
			
		}*/
		
		/**
		 * This is the function for parsing card template xml and update into DB
		 * 
		 * @functionName onThemesLoaded
		 * @creationDate Sep 1, 2012
		 * @author micmac
		 * @params event:CompleteEvent
		 */
		/*private function onCardTemplatesLoaded(event:CompleteEvent):void
		{
			
			var cardTemplateXMLVO:CardTemplateXMLVO = _versionDetails[VersionChecker.CARD_TEMPLATE_VERSION_DETAILS];
			
			IConfigLoader( event.target ).removeEventListener( CompleteEvent.COMPLETE, onThemesLoaded );
			
			//Pars cards xml and add it to database
			trace( XML( ConfigLoader(event.object).data ) );
			var iCardDBManger:ICardDBManager = new CardDBManager();
			iCardDBManger.process(cardTemplateXMLVO.cardTemplateVersion, XML( ConfigLoader(event.object).data).toString() );
			//-----------------
			
			dispatchEvent(new CustomCompleteEvent(CustomCompleteEvent.COMPLETED, "Versioned XML handling complete", true, true));
			
			
		}*/
		
		/**
		 * This is the function for send event curresponding to card template load fault
		 * 
		 * @functionName onCardTemplatesLoadFailed
		 * @creationDate Nov 12, 2012
		 * @author micmac
		 * @params event:LoadFaultEvent
		 */
		/*private function onCardTemplatesLoadFailed(event:LoadFaultEvent):void
		{
			
			dispatchEvent(new CustomErrorEvent(CustomErrorEvent.ERROR_OCCURED, "Themes XML load failed"));
			
		}*/
		
		
		//////////////////////////////////////////////////END:Updating card template details/////////////////////////////////////////////
		
		
	}
	
}